package com.huxiu.yd;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.huxiu.yd.net.GsonRequest;
import com.huxiu.yd.net.NetworkConstants;
import com.huxiu.yd.net.model.DiscoveryItem;
import com.huxiu.yd.net.responses.DiscoveryListResponse;
import com.huxiu.yd.utils.Constants;
import com.huxiu.yd.utils.ErrorResponseException;
import com.huxiu.yd.utils.ImageUtils;
import com.huxiu.yd.utils.Utils;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by yao on 15/8/18:下午10:30.
 */
public class MyMassiveTestActivity extends BaseActivity implements PullToRefreshBase
        .OnRefreshListener2<ListView>, AdapterView.OnItemClickListener {

    @InjectView(R.id.back)
    ImageView back;

    @InjectView(R.id.title)
    TextView title;

    @InjectView(R.id.list)
    PullToRefreshListView list;

    @InjectView(android.R.id.empty)
    TextView empty;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_massive_test);
        ButterKnife.inject(this);
        back.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        title.setText(R.string.my_massive_tests);
        adapter = new DiscoveryAdapter();
        list.setAdapter(adapter);
        list.setOnRefreshListener(this);
        empty.setText(R.string.you_did_not_attend_any_test);
        list.setEmptyView(empty);
        list.setState(PullToRefreshBase.State.INIT_REFRESHING, true);
        list.setOnItemClickListener(this);
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        getItems(0);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        getItems(currentPage + 1);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(this, DiscoveryDetailActivity.class);
        intent.putExtra(Constants.MASSIVE_TEST_ITEM_KEY, items.get(position - 1).toString());
        startActivity(intent);
    }

    /**
     * This class contains all butterknife-injected Views & Layouts from layout file
     * 'my_massive_test_list_item.xml'
     * for easy to all layout elements.
     *
     * @author ButterKnifeZelezny, plugin for Android Studio by Avast Developers (http://github
     *         .com/avast)
     */
    static class ViewHolder {
        @InjectView(R.id.image)
        ImageView image;

        @InjectView(R.id.line1)
        TextView line1;

        @InjectView(R.id.line2)
        TextView line2;

        ViewHolder(View view) {
            ButterKnife.inject(this, view);
        }
    }

    private int currentPage = 0;

    private void getItems(final int page) {
        String url = NetworkConstants.MEMBER_URL;
        Map<String, String> params = new HashMap<>();
        params.put("act", "user_topic");
        params.put("opt", "topic_activity");
        params.put("page", Integer.toString(page));
        GsonRequest<DiscoveryListResponse> request = new GsonRequest<>(url, Request.Method.POST,
                DiscoveryListResponse.class, true, params, new Response
                .Listener<DiscoveryListResponse>() {
            @Override
            public void onResponse(DiscoveryListResponse response) {
                if (response.isSuccess()) {
                    if (page == 0) {
                        items.clear();
                    }
                    Collections.addAll(items, response.data);
                    adapter.notifyDataSetChanged();
                    currentPage = response.page;
                    refreshComplete();
                }
            }
        }, mErrorListener);
        mQueue.add(request);
//        mQueue.start();
    }

    protected Response.ErrorListener mErrorListener = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            dismissProgress();
            Throwable t = error.getCause();
            if (!(t instanceof ErrorResponseException)) {
                Utils.showToast(R.string.generic_failure);
            }
            refreshComplete();
        }
    };

    private void refreshComplete() {
        list.postDelayed(new Runnable() {
            @Override
            public void run() {
                list.onRefreshComplete();
            }
        }, 100);
    }

    private List<DiscoveryItem> items = new ArrayList<>();

    private DiscoveryAdapter adapter;

    private class DiscoveryAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return items.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            ViewHolder vh;
            if (view == null) {
                view = getLayoutInflater().inflate(R.layout.my_massive_test_list_item, parent,
                        false);
                vh = new ViewHolder(view);
                view.setTag(vh);
            }
            vh = (ViewHolder) view.getTag();
            DiscoveryItem item = items.get(position);
            ImageLoader.getInstance().displayImage(item.image, vh.image, ImageUtils
                    .getProductDisplayOption(R.drawable.default_product_image));
            vh.line1.setText(item.title);
            vh.line2.setTextColor(getResources().getColor(item.getApplyStatusColor()));
            vh.line2.setText(item.getApplyStatusString());
            return view;
        }
    }
}